<template>
  <view class="user-detail">
    <view v-if="loading" class="loading-container">
      <AppLoading text="正在加载用户信息..." />
    </view>

    <view v-else-if="!userInfo" class="error-container">
      <view class="error-content">
        <text class="error-text">用户不存在或已被删除</text>
        <button class="back-btn" @click="handleBack">返回用户列表</button>
      </view>
    </view>

    <view v-else class="detail-container">
      <!-- 用户基本信息卡片 -->
      <Card class="user-info-card" title="用户信息">
        <template #extra>
          <view class="status-section">
            <Badge
              :text="getStatusText(userInfo.status)"
              :type="getStatusType(userInfo.status)"
            />
          </view>
        </template>

        <view class="user-info-content">
          <view class="user-avatar">
            <image
              v-if="userInfo.avatar"
              :src="userInfo.avatar"
              class="avatar-img"
              mode="aspectFill"
              @click="previewAvatar(userInfo.avatar)"
            />
            <view v-else class="avatar-placeholder">
              <text class="avatar-text">{{ getAvatarText(userInfo.realName) }}</text>
            </view>
            <button
              v-if="isEditable"
              class="avatar-edit-btn"
              @click="handleAvatarEdit"
            >
              更换头像
            </button>
          </view>

          <view class="basic-info">
            <view class="info-item">
              <text class="label">用户名：</text>
              <text class="value">{{ userInfo.username }}</text>
            </view>
            <view class="info-item">
              <text class="label">真实姓名：</text>
              <text class="value">{{ userInfo.realName }}</text>
            </view>
            <view class="info-item">
              <text class="label">角色：</text>
              <Badge
                :text="getRoleText(userInfo.role)"
                :type="getRoleBadgeType(userInfo.role)"
              />
            </view>
            <view class="info-item">
              <text class="label">手机号：</text>
              <text class="value">{{ userInfo.phone || '未设置' }}</text>
            </view>
            <view class="info-item">
              <text class="label">邮箱：</text>
              <text class="value">{{ userInfo.email || '未设置' }}</text>
            </view>
            <view class="info-item">
              <text class="label">创建时间：</text>
              <text class="value">{{ formatDate(userInfo.createdTime) }}</text>
            </view>
            <view class="info-item">
              <text class="label">最后登录：</text>
              <text class="value">{{ formatDate(userInfo.lastLoginTime) || '从未登录' }}</text>
            </view>
          </view>
        </view>
      </Card>

      <!-- 操作按钮区域 -->
      <Card v-if="isEditable" class="action-card" title="操作管理">
        <view class="action-buttons">
          <button
            class="action-btn edit-btn"
            @click="handleEdit"
          >
            编辑信息
          </button>
          <button
            class="action-btn password-btn"
            @click="handleResetPassword"
          >
            重置密码
          </button>
          <button
            v-if="userInfo.status !== 'ACTIVE'"
            class="action-btn activate-btn"
            @click="handleActivate"
          >
            激活用户
          </button>
          <button
            v-if="userInfo.status === 'ACTIVE'"
            class="action-btn deactivate-btn"
            @click="handleDeactivate"
          >
            禁用用户
          </button>
          <button
            class="action-btn delete-btn"
            @click="handleDelete"
          >
            删除用户
          </button>
        </view>
      </Card>

      <!-- 状态管理卡片 -->
      <Card v-if="isEditable" class="status-card" title="状态管理">
        <view class="status-info">
          <view class="status-item">
            <text class="status-label">当前状态：</text>
            <Badge
              :text="getStatusText(userInfo.status)"
              :type="getStatusType(userInfo.status)"
            />
          </view>
          <view class="status-description">
            <text class="description-title">状态说明：</text>
            <text class="description-text">{{ getStatusDescription(userInfo.status) }}</text>
          </view>
        </view>
      </Card>

      <!-- 用户权限卡片 -->
      <Card class="permission-card" title="权限信息">
        <view class="permission-info">
          <view class="permission-item">
            <text class="permission-label">角色权限：</text>
            <text class="permission-value">{{ getRolePermission(userInfo.role) }}</text>
          </view>
          <view class="permission-detail">
            <text class="detail-title">权限详情：</text>
            <view class="permission-list">
              <text
                v-for="(permission, index) in getRolePermissions(userInfo.role)"
                :key="index"
                class="permission-item-text"
              >
                • {{ permission }}
              </text>
            </view>
          </view>
        </view>
      </Card>
    </view>

    <!-- 自定义导航栏按钮 -->
    <view class="nav-actions">
      <button
        v-if="!isEditable && userInfo"
        class="nav-btn"
        @click="handleEdit"
      >
        编辑
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { userAPI, type User } from '@/api/user'
import AppLoading from '@/components/common/AppLoading.vue'
import Card from '@/components/common/Card.vue'
import Badge from '@/components/common/Badge.vue'

// 响应式数据
const loading = ref(true)
const userInfo = ref<User | null>(null)
const userId = ref<string>('')

// 计算属性
const isEditable = computed(() => {
  // TODO: 根据当前用户权限判断是否可编辑
  return true
})

// 方法
/**
 * 获取用户信息
 */
const fetchUserInfo = async () => {
  if (!userId.value) {
    loading.value = false
    return
  }

  try {
    loading.value = true
    const response = await userAPI.getUserById(userId.value)
    if (response.code === 200 && response.data) {
      userInfo.value = response.data
    } else {
      userInfo.value = null
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    userInfo.value = null
    uni.showToast({
      title: '获取用户信息失败',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

/**
 * 处理返回
 */
const handleBack = () => {
  uni.navigateBack()
}

/**
 * 处理编辑
 */
const handleEdit = () => {
  if (!userInfo.value) return
  uni.navigateTo({
    url: `/pages/admin/user-edit?id=${userInfo.value.id}`
  })
}

/**
 * 处理头像编辑
 */
const handleAvatarEdit = () => {
  // TODO: 实现头像编辑功能
  uni.showToast({
    title: '头像编辑功能开发中',
    icon: 'none'
  })
}

/**
 * 处理重置密码
 */
const handleResetPassword = () => {
  if (!userInfo.value) return

  uni.showModal({
    title: '重置密码',
    content: `确定要重置用户"${userInfo.value.realName}"的密码吗？`,
    placeholderText: '请输入新密码',
    editable: true,
    success: async (res) => {
      if (res.confirm && res.content) {
        try {
          const response = await userAPI.resetUserPassword(
            userInfo.value!.id,
            res.content
          )
          if (response.code === 200) {
            uni.showToast({
              title: '密码重置成功',
              icon: 'success'
            })
          }
        } catch (error) {
          console.error('重置密码失败:', error)
          uni.showToast({
            title: '重置密码失败',
            icon: 'error'
          })
        }
      }
    }
  })
}

/**
 * 处理激活用户
 */
const handleActivate = async () => {
  if (!userInfo.value) return

  uni.showModal({
    title: '激活用户',
    content: `确定要激活用户"${userInfo.value.realName}"吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await userAPI.activateUser(userInfo.value!.id)
          if (response.code === 200) {
            uni.showToast({
              title: '用户激活成功',
              icon: 'success'
            })
            fetchUserInfo()
          }
        } catch (error) {
          console.error('激活用户失败:', error)
          uni.showToast({
            title: '激活用户失败',
            icon: 'error'
          })
        }
      }
    }
  })
}

/**
 * 处理禁用用户
 */
const handleDeactivate = async () => {
  if (!userInfo.value) return

  uni.showModal({
    title: '禁用用户',
    content: `确定要禁用用户"${userInfo.value.realName}"吗？禁用后该用户将无法登录。`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await userAPI.deactivateUser(userInfo.value!.id)
          if (response.code === 200) {
            uni.showToast({
              title: '用户禁用成功',
              icon: 'success'
            })
            fetchUserInfo()
          }
        } catch (error) {
          console.error('禁用用户失败:', error)
          uni.showToast({
            title: '禁用用户失败',
            icon: 'error'
          })
        }
      }
    }
  })
}

/**
 * 处理删除用户
 */
const handleDelete = () => {
  if (!userInfo.value) return

  uni.showModal({
    title: '删除用户',
    content: `确定要删除用户"${userInfo.value.realName}"吗？此操作不可恢复。`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await userAPI.deleteUser(userInfo.value!.id)
          if (response.code === 200) {
            uni.showToast({
              title: '用户删除成功',
              icon: 'success'
            })
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          }
        } catch (error) {
          console.error('删除用户失败:', error)
          uni.showToast({
            title: '删除用户失败',
            icon: 'error'
          })
        }
      }
    }
  })
}

/**
 * 预览头像
 */
const previewAvatar = (avatarUrl: string) => {
  uni.previewImage({
    urls: [avatarUrl],
    current: avatarUrl
  })
}

/**
 * 获取头像文字
 */
const getAvatarText = (name: string) => {
  if (!name) return '?'
  return name.charAt(0).toUpperCase()
}

/**
 * 获取角色文本
 */
const getRoleText = (role: string) => {
  const roleMap: Record<string, string> = {
    'ADMIN': '超级管理员',
    'SCHOOL_ADMIN': '学校管理员',
    'TEACHER': '教师',
    'PARENT': '家长'
  }
  return roleMap[role] || role
}

/**
 * 获取角色徽章类型
 */
const getRoleBadgeType = (role: string) => {
  const typeMap: Record<string, string> = {
    'ADMIN': 'danger',
    'SCHOOL_ADMIN': 'warning',
    'TEACHER': 'primary',
    'PARENT': 'success'
  }
  return typeMap[role] || 'info'
}

/**
 * 获取状态文本
 */
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'ACTIVE': '正常',
    'INACTIVE': '禁用',
    'LOCKED': '锁定'
  }
  return statusMap[status] || status
}

/**
 * 获取状态类型
 */
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    'ACTIVE': 'success',
    'INACTIVE': 'error',
    'LOCKED': 'warning'
  }
  return typeMap[status] || 'info'
}

/**
 * 获取状态描述
 */
const getStatusDescription = (status: string) => {
  const descMap: Record<string, string> = {
    'ACTIVE': '用户正常使用，可正常登录系统',
    'INACTIVE': '用户已被禁用，无法登录系统',
    'LOCKED': '用户已被锁定，无法登录系统'
  }
  return descMap[status] || '未知状态'
}

/**
 * 获取角色权限描述
 */
const getRolePermission = (role: string) => {
  const permissionMap: Record<string, string> = {
    'ADMIN': '系统全部权限',
    'SCHOOL_ADMIN': '学校管理权限',
    'TEACHER': '班级教学权限',
    'PARENT': '学生查看权限'
  }
  return permissionMap[role] || '未知权限'
}

/**
 * 获取角色权限列表
 */
const getRolePermissions = (role: string): string[] => {
  const permissionsMap: Record<string, string[]> = {
    'ADMIN': [
      '用户管理',
      '学校管理',
      '班级管理',
      '系统设置',
      '数据统计',
      '日志查看'
    ],
    'SCHOOL_ADMIN': [
      '教师管理',
      '班级创建',
      '学生管理',
      '家长管理',
      '教学安排',
      '成绩管理'
    ],
    'TEACHER': [
      '班级管理',
      '学生档案',
      '成绩录入',
      '表扬批评',
      '通知发布',
      '家长沟通'
    ],
    'PARENT': [
      '查看学生信息',
      '查看成绩',
      '查看档案',
      '接收通知',
      '与教师沟通'
    ]
  }
  return permissionsMap[role] || []
}

/**
 * 格式化日期
 */
const formatDate = (dateString?: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  // @ts-ignore
  const options = currentPage.options || {}

  userId.value = options.id || ''

  fetchUserInfo()
})
</script>

<style lang="scss" scoped>
.user-detail {
  min-height: 100vh;
  background: #f5f7fa;
  padding-bottom: 20px;
}

.loading-container,
.error-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
}

.error-content {
  text-align: center;

  .error-text {
    font-size: 16px;
    color: #666;
    margin-bottom: 20px;
    display: block;
  }

  .back-btn {
    padding: 10px 20px;
    background: #1890ff;
    color: #ffffff;
    border: none;
    border-radius: 6px;
    font-size: 14px;
  }
}

.detail-container {
  padding: 16px;
}

.user-info-card {
  margin-bottom: 16px;

  .user-info-content {
    .user-avatar {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 24px;

      .avatar-img {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        background: #f0f0f0;
        margin-bottom: 12px;
      }

      .avatar-placeholder {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        background: #1890ff;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 12px;

        .avatar-text {
          color: #ffffff;
          font-size: 36px;
          font-weight: 600;
        }
      }

      .avatar-edit-btn {
        padding: 6px 12px;
        background: #f0f0f0;
        color: #666;
        border: none;
        border-radius: 4px;
        font-size: 12px;
      }
    }

    .basic-info {
      .info-item {
        display: flex;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .label {
          font-size: 14px;
          color: #666;
          min-width: 80px;
        }

        .value {
          flex: 1;
          font-size: 14px;
          color: #333;
        }
      }
    }
  }
}

.action-card {
  margin-bottom: 16px;

  .action-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;

    .action-btn {
      flex: 1;
      min-width: 120px;
      padding: 10px 16px;
      border: none;
      border-radius: 6px;
      font-size: 14px;
      color: #ffffff;

      &.edit-btn {
        background: #1890ff;
      }

      &.password-btn {
        background: #722ed1;
      }

      &.activate-btn {
        background: #52c41a;
      }

      &.deactivate-btn {
        background: #fa8c16;
      }

      &.delete-btn {
        background: #f5222d;
      }
    }
  }
}

.status-card {
  margin-bottom: 16px;

  .status-info {
    .status-item {
      display: flex;
      align-items: center;
      margin-bottom: 16px;

      .status-label {
        font-size: 14px;
        color: #666;
        margin-right: 8px;
      }
    }

    .status-description {
      .description-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;
        display: block;
      }

      .description-text {
        font-size: 13px;
        color: #999;
        line-height: 1.5;
      }
    }
  }
}

.permission-card {
  .permission-info {
    .permission-item {
      display: flex;
      align-items: center;
      margin-bottom: 16px;

      .permission-label {
        font-size: 14px;
        color: #666;
        margin-right: 8px;
      }

      .permission-value {
        font-size: 14px;
        color: #1890ff;
        font-weight: 500;
      }
    }

    .permission-detail {
      .detail-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 12px;
        display: block;
      }

      .permission-list {
        .permission-item-text {
          font-size: 13px;
          color: #666;
          line-height: 1.6;
          display: block;
          margin-bottom: 4px;
        }
      }
    }
  }
}

.nav-actions {
  position: fixed;
  top: 50%;
  right: 16px;
  transform: translateY(-50%);

  .nav-btn {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: #1890ff;
    color: #ffffff;
    border: none;
    font-size: 14px;
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
  }
}

// 响应式设计
@media (max-width: 480px) {
  .detail-container {
    padding: 12px;
  }

  .action-buttons {
    .action-btn {
      min-width: 100px;
      padding: 8px 12px;
      font-size: 13px;
    }
  }

  .nav-actions {
    .nav-btn {
      width: 40px;
      height: 40px;
      font-size: 12px;
    }
  }
}
</style>